package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.feign.AdminFeign;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotArticlesService;
import com.heima.common.constants.article.ArticleConstants;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vo.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @作者 itcast
 * @创建日期 2020/12/23 15:35
 **/
@Service
@Transactional
public class HotArticlesServiceImpl implements HotArticlesService {

    @Autowired
    private ApArticleMapper apArticleMapper;

    /**
     * 定时计算热点文章数据
     */
    @Override
    public void computeHotArticle() {
        //1. 查询前5天的文章数据
        String dataParam = DateTime.now().minusDays(5).toString("yyyy-MM-dd 00:00:00");
        List<ApArticle> apArticles = apArticleMapper.selectList(
                Wrappers.<ApArticle>lambdaQuery().gt(ApArticle::getPublishTime, dataParam)
        );
        //2  计算文章分值
        List<HotArticleVo> hotArticleVoList = computeHotArticle(apArticles);
        //3. 为每一个频道缓存热点较高的30条文章数据
        cacheTagToRedis(hotArticleVoList);
    }
    @Autowired
    AdminFeign adminFeign;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    /**
     * 为每一个频道缓存热点较高的30条文章数据
     * 存入到redis中
     * @param hotArticleVoList
     */
    private void cacheTagToRedis(List<HotArticleVo> hotArticleVoList) {
        ResponseResult responseResult = adminFeign.selectAllChannel();
        // 获取全部频道列表
        List<AdChannel> adChannels = JSONArray.parseArray(JSON.toJSONString(responseResult.getData()), AdChannel.class);
        for (AdChannel adChannel : adChannels) {
            // 为每个频道 缓存对应的热点文章
            List<HotArticleVo> hotListByChannel = hotArticleVoList.stream()
                    .filter(hotArticleVo -> adChannel.getId() == hotArticleVo.getChannelId())
                    .sorted((o1, o2) -> o2.getScore().compareTo(o1.getScore()))
                    .limit(30)
                    .collect(Collectors.toList());
            // 缓存指定频道的热点文章列表
            stringRedisTemplate.boundValueOps(ArticleConstants.HOT_ARTICLE_FIRST_PAGE+adChannel.getId()).set(JSON.toJSONString(hotListByChannel));
        }
        // 最近5天文章中 最热的30篇文章
        List<HotArticleVo> hotList = hotArticleVoList.stream()
                .sorted((o1, o2) -> o2.getScore().compareTo(o1.getScore())) // 按照得分降序排序
                .limit(30)  // 取前30条数据
                .collect(Collectors.toList()); // 转为集合
        stringRedisTemplate.boundValueOps(ArticleConstants.HOT_ARTICLE_FIRST_PAGE+ArticleConstants.DEFAULT_TAG).set(JSON.toJSONString(hotList));
    }
    /**
     * 计算文章分值:
     *   根据行为参数进行计算
     *      阅读行为 0
     *      点赞行为 3
     *      评论行为 5
     *      收藏行为 8
     * @param apArticles
     * @return
     */
    private List<HotArticleVo> computeHotArticle(List<ApArticle> apArticles) {
        List<HotArticleVo> hotArticleVoList = new ArrayList<>();
        if (apArticles!=null&&!apArticles.isEmpty()) {
            for (ApArticle apArticle : apArticles) {
                HotArticleVo hotArticleVo = new HotArticleVo();
                // 拷贝属性
                BeanUtils.copyProperties(apArticle,hotArticleVo);
                // 计算得分
                Integer score = computeScore(apArticle);
                hotArticleVo.setScore(score);
                hotArticleVoList.add(hotArticleVo);
            }
        }
        return hotArticleVoList;
    }

    /**
     * 计算得分
     *
     * score = (阅读量) + (点赞量*点赞权重) + (评论量*评论权重) + (收藏量*收藏权重)
     *
     * @param apArticle
     * @return
     */
    private Integer computeScore(ApArticle apArticle) {
        Integer score = 0;
        if(apArticle.getViews()!=null){
            score += apArticle.getViews();
        }
        if(apArticle.getLikes()!=null){
            score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if(apArticle.getComment()!=null){
            score += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        if(apArticle.getCollection()!=null){
            score += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }
        return score;
    }
}
